package com.youdianstar.app.ui.pay

import android.app.Dialog
import android.view.View

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityPaymentResultBinding
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.getObject
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.*
import com.youdianstar.app.entity.OrderInfo

import com.youdianstar.app.entity.PaymentResult
import com.youdianstar.app.util.WalletDialogUtil
import com.youdianstar.app.ui.MainActivity
import com.youdianstar.app.ui.ScanActivity
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.ex.parseTx
import com.youdianstar.app.util.DataHelperEx

import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: PaymentResultActivity
 * Author: 82149 Create: 2021/11/27 17:46
 * Changes (from 2021/11/27)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class PaymentResultActivity : BaseActivity<ActivityPaymentResultBinding, PaymentViewModel>() {
    override fun layoutId(): Int = R.layout.activity_payment_result

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): PaymentViewModel {
        val model: PaymentViewModel by viewModel()
        return model
    }

    private var isResSuccess = true
    private var payBisType = 0
    private var resultInfo: PaymentResult? = null

    private var receiptDialog: Dialog? = null

    override fun initViewLayout() {
        super.initViewLayout()
        mBinding.headBar.initTitle(this, title = "", showInner = false)
        mBinding.headBar.setBackUnable()

    }

    override fun initData() {
        super.initData()
        isResSuccess = intent.getBooleanExtra(Extra.IT_RESULT, true)
        payBisType = intent.getIntExtra(Extra.IT_TYPE, BisType.Bis_Rent)
        resultInfo = intent.getObject(Extra.IT_DATA)

        mBinding.ivResult.setImageResource(if (isResSuccess) R.mipmap.ic_pay_success else R.mipmap.ic_pay_failed)
        mBinding.tvResultDes.text = getString(if (isResSuccess) R.string.pay_paySucc else R.string.pay_payFail)
        mBinding.tvResultDes.setTextColor(getViewColor(this,if (isResSuccess) R.color.color_39404D else R.color.color_889DBB))
        if (payBisType== BisType.Bis_Deposit || payBisType== BisType.Bis_ChargingCard){
            mBinding.llPaymentOrder.visibility = View.GONE
        }else{
            if (isResSuccess){
                DataAppManager.instance.rentEndTag = true
            }
            mBinding.llPaymentOrder.visibility = View.VISIBLE
        }

        resultInfo?.let { result ->
            val symbolStr = DataAppManager.instance.symbolTx()
            if (null == result.orderJson){
                mBinding.tvOrderDuration.text = "--"
                mBinding.tvOrignalFees.text = "$symbolStr 0.00"
                mBinding.txCouponAndDiscount.visibility = View.GONE
                mBinding.clCouponFree.visibility = View.GONE
                mBinding.clPromoFree.visibility = View.GONE
                mBinding.clPlatformDis.visibility = View.GONE
                mBinding.lineCoupon.visibility = View.GONE
            }
            result.orderJson?.let { json ->
                val order = GsonUtil.jsonToBean(json,OrderInfo::class.java)
                /*订单信息*/
                if (payBisType != BisType.Bis_Deposit){
                    //订单计时
                    val timeArray = DateUtil.time2ArrayTime(order.getOrderDuration() * 1000)
                    val dayStr = DateUtil.time0format(timeArray[0])
                    val hrStr = DateUtil.time0format(timeArray[1])
                    val minStr = DateUtil.time0format(timeArray[2])
                    val secStr = DateUtil.time0format(timeArray[3])
                    if (timeArray[0] > 0) {
                        if (timeArray[0] > 1) {
                            mBinding.tvOrderDuration.text = String.format(getString(R.string.Order_duration_days), secStr, minStr, hrStr, dayStr)
                        } else {
                            mBinding.tvOrderDuration.text = String.format(getString(R.string.Order_duration_day), secStr, minStr, hrStr, dayStr)
                        }
                    } else {
                        mBinding.tvOrderDuration.text = String.format(getString(R.string.Order_duration_text), secStr, minStr, hrStr)
                    }
                    //租借金额
                    mBinding.tvOrignalFees.text = symbolStr+MathUtil.round(order.orderAmountValue())
                }

                /*结算信息*/
                //充电卡优惠
                mBinding.clChargingFree.visibility = if (order.chargeCardDuration > 0) View.VISIBLE else View.GONE
                mBinding.tvCardValue.text = getString(R.string.coupon_freeUsage) +" "+ DataHelperEx.chargingFreeTx(this,order.chargeCardDuration)
                //优惠券折扣 : 时长免费 金额优惠 折扣租金 (只显示折扣了多少金额)
                mBinding.clCouponFree.visibility = if (order.userCouponId > 0) View.VISIBLE else View.GONE
                val couponDeductTx :String = if (null==order.userCouponInfo) "$symbolStr ${MathUtil.round(order.couponAmountValue())}" else {
                    if (null!=order.userCouponInfo.deduction)
                        DataHelperEx.couponDeductTime(this, symbolStr, order.userCouponInfo.deduction,order.couponAmountValue())
                    else
                        "--"
                }
                mBinding.tvCouponValue.text = couponDeductTx
                //优惠码折扣
                mBinding.clPromoFree.visibility = if (order.userPromoCodeId > 0) View.VISIBLE else View.GONE
                val promoDeductTx :String = if (null==order.userPromoCodeInfo) "$symbolStr ${MathUtil.round(order.promoAmountValue())}" else {
                    if (null!=order.userPromoCodeInfo.deduction)
                        DataHelperEx.couponDeductTime(this, symbolStr, order.userPromoCodeInfo.deduction,order.promoAmountValue())
                    else
                        "--"
                }
                mBinding.tvPromoValue.text = promoDeductTx
                //平台折扣金额:平台设置优惠金额/免单
                mBinding.clPlatformDis.visibility = if (order.platAmountValue() > 0) View.VISIBLE else View.GONE
                mBinding.tvPlatAmount.text = symbolStr+MathUtil.round(order.platAmountValue())

                if (result.type == BisType.Bis_Deposit
                    || (order.couponAmountValue()==0.0 && order.promoAmountValue()==0.0 && order.platAmountValue()==0.0)){
                    mBinding.txCouponAndDiscount.visibility = View.GONE
                    mBinding.lineCoupon.visibility = View.GONE
                }
            }

            /*结算信息*/
            //1.交易流水编号
            mBinding.tvBillingNo.text = result.orderNo?:"--"
            //2.业务
            val typeText = when(result.type){
                BisType.Bis_Deposit ->{
                    getString(R.string.pay_deposit)
                }
                BisType.Bis_Rent ->{
                    getString(R.string.pay_rental)
                }
                BisType.Bis_Loss ->{
                    getString(R.string.pay_powerbank)
                }
                BisType.Bis_ChargingCard ->{
                    getString(R.string.charge_card)
                }
                else ->{
                    "--"
                }
            }
            mBinding.tvBisType.text = typeText
            //税金
            if (result.tax>0){
                mBinding.clPaymentTax.visibility = View.VISIBLE
                mBinding.txPaymentTax.text = getString(R.string.pay_tax) + " "+MathUtil.round(result.tax) + "%"
                mBinding.tvPaymentTax.text = symbolStr + MathUtil.round(result.taxAmount)
                mBinding.txActualRental.text = getString(R.string.order_paymentAmount) + " ("+getString(R.string.pay_includingTax)+")"
            }else{
                mBinding.clPaymentTax.visibility = View.GONE
                mBinding.txActualRental.text = getString(R.string.order_paymentAmount)
            }
            //3.实际支付金额
            mBinding.tvActualFees.text = symbolStr + MathUtil.round(result.amount)
            //4.支付方式
            var methodText = ""
            if (!result.isFree){
                when (result.paymentMethod) {
                    DataCode.Type_NewCard, DataCode.Type_Card -> {
                        val cardNo: String = result.bankNo ?: "--"
                        if (!StrUtil.isEmpty(cardNo))
                            methodText = getString(R.string.wallet_type_bankcard) + "($cardNo)"
                        else
                            methodText = getString(R.string.wallet_type_bankcard)
                    }
                    DataCode.Type_Google -> methodText = getString(R.string.wallet_type_googlepay)
                    DataCode.Type_Paypal -> methodText = getString(R.string.wallet_type_paypal)
                }
            }
            //支付方式: 失败-> 隐藏支付方式
            mBinding.clPaymentMethod.visibility = if (isResSuccess) View.VISIBLE else View.GONE
            //支付方式: 免单不显示支付方式(同步企业版的)
            if (StrUtil.isEmpty(methodText)){
                mBinding.tvPaymentMethod.text = "--"
            }else{
                mBinding.tvPaymentMethod.text = String.format(getString(R.string.pay_paidBy),methodText)
            }

            //5.失败原因
            mBinding.tvFalseReason.text = result.failedReason.parseTx()
            mBinding.clFalseReason.visibility = if (isResSuccess) View.GONE else View.VISIBLE

            //底部 按钮
            if (isResSuccess) {
                mBinding.btnReceipt.text = getString(R.string.order_receipt)
                mBinding.btnReceipt.visibility = if (!result.isFree) View.VISIBLE else View.GONE //免单不显示收据
                if (result.type == BisType.Bis_Deposit && DataAppManager.instance.rentScanTag){
                    mBinding.btnHomePage.text = getString(R.string.home_scan2rent)
                }else
                    mBinding.btnHomePage.text = getString(R.string.order_homePage)
            } else {
                mBinding.btnReceipt.text = getString(R.string.order_homePage)
                mBinding.btnHomePage.text = getString(R.string.home_gotoPay)
            }
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.receiptResultLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mBinding.btnReceipt.isClickable = false
                toastShow(getString(R.string.public_success))

                if (null!=resultInfo && resultInfo!!.type == BisType.Bis_Deposit
                    && DataAppManager.instance.rentScanTag){
                    startActivity<ScanActivity>(Extra.IT_TYPE to BisType.Scan_Rent)
                } else
                    startActivity<MainActivity>()  //回主页
                finish()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }

    override fun initClickEvent() {
        mBinding.btnReceipt.setThrottleListener {
            if (isResSuccess) {
                //发票 弹框确认发送邮件
                showReceiptDialog()
            } else {
                //失败 回到主页
                startActivity<MainActivity>()
                finish()
            }
        }

        mBinding.btnHomePage.setThrottleListener {
            if (isResSuccess) {
                //成功 回到主页 or 扫码流程
                if (null!=resultInfo && resultInfo!!.type == BisType.Bis_Deposit
                        && DataAppManager.instance.rentScanTag){
                    startActivity<ScanActivity>(Extra.IT_TYPE to BisType.Scan_Rent)
                } else
                    startActivity<MainActivity>()
                finish()
            } else {
                //失败 返回继续支付
                finish()
            }
        }
    }

    private fun showReceiptDialog() {
        resultInfo?.let { result ->
            var emailStr: String? = null
            val user = DataAppManager.instance.getUser()
            user?.let {
                emailStr = it.receiptEmail
            }
            receiptDialog = WalletDialogUtil.instance.showReceiptDialog(this, emailStr ?: "") { email ->
                    mViewModel.sendPaymentReceipt(orderNo = result.payOrderNo ?: "", email = email)
                }
        }
    }


    override fun onPause() {
        super.onPause()
        receiptDialog?.let {
            if (it.isShowing)
                it.dismiss()
        }
    }
}